package com.example.clienteclinicav2;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;


import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListarClienteActivity extends ListActivity {
		
		//definir estrutura de la lista
			public class Node{
				public String rutPaciente;
				public String nombrePaciente;
				public String direccionPaciente;
			}
	    //Arrreglo
		private static ArrayList<Node>mArray = new ArrayList<ListarClienteActivity.Node>();
		private MyAdapter mAdapter = null;
		private String URL = "http://192.168.0.12:8080/ServicioPrestacionesClinica/services/PacienteORM";
		private String NAMESPACE = "http://capaservicio";
	
		

		@Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        mArray.clear();
	        new ObtenerPacientesBackground().execute();
	    }
		
		public void carga()
		{
			mAdapter = new MyAdapter(this);
	        this.setListAdapter(mAdapter);
		}
		
		protected void onListItemClick(ListView l,View v, int position, long id){
			//pasar a la otra activity
			
			Intent iniciarActividad = new Intent(this, ModificarPacienteActivity.class );
			iniciarActividad.putExtra("rut", mArray.get(position).rutPaciente);
			iniciarActividad.putExtra("nombre", mArray.get(position).nombrePaciente);
			iniciarActividad.putExtra("direccion", mArray.get(position).direccionPaciente);
	        startActivity(iniciarActividad);  
			
		}
		
		public class MyAdapter extends BaseAdapter
		{

			private Context mContext;
			
			public MyAdapter(Context c){
				Log.i("adapter", "cargando contexto");
				mContext = c;
			}
			public int getCount() {
				// TODO Auto-generated method stub
				return mArray.size();
			}
			public Object getItem(int posicion) {
				// TODO Auto-generated method stub
				return mArray.get(posicion);
			}
			public long getItemId(int position) {
				// TODO Auto-generated method stub
				return 0;
			}
			
			public View getView(int position, View convertView, ViewGroup parent) {
				// TODO Auto-generated method stub
				View view = null;
				
				if(convertView==null){
					//Log.i("adapter", "null view");
					LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = inflater.inflate(R.layout.activity_listar_cliente, null);
				}else{
					Log.i("adapter", "view");
					view = convertView;	
				}
				Log.i("adapter", "Cargando listado");
				TextView title = (TextView) view.findViewById(R.id.nombre);
				title.setText(mArray.get(position).nombrePaciente);
				
				TextView Tdesciption = (TextView) view.findViewById(R.id.direccion);
				Tdesciption.setText(mArray.get(position).direccionPaciente);
				
				return view;
			}
			
		}	
		
		
		 class ObtenerPacientesBackground extends AsyncTask<Void, Void, String>{
		    	
		    	private ProgressDialog progressDialog;

				@Override
				protected void onPreExecute() {
		    		progressDialog = ProgressDialog.show(
		    				ListarClienteActivity.this,
		    				"Prescli V1.0", 
		    				"Espere mientras se cargan los pacientes...", 
		    				true);
					super.onPreExecute();
				}

				@Override
				protected String doInBackground(Void... params) {

					String resultadoJSON="";
			    	String METHOD_NAME = "obtenerPacientes";
			    	String SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
					SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
					SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
					soapEnvelope.dotNet = true;
					soapEnvelope.implicitTypes =true;
					soapEnvelope.setOutputSoapObject(request);

					HttpTransportSE aht = new HttpTransportSE(URL);
					Log.d("Pacientes SOAP", "Iniciando Consulta");
					try {
						aht.call(SOAP_ACTION, soapEnvelope);
						SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
						resultadoJSON = resultString.toString();
						Log.d("Pacientes SOAP", "Finalizando Consulta");
						
						
					} catch (IOException e) {
						e.printStackTrace();
					} catch (XmlPullParserException e) {
						e.printStackTrace();
					}
			    
					return resultadoJSON;
				}

				@Override
				protected void onPostExecute(String result) {
					super.onPostExecute(result);
					progressDialog.dismiss();
					if("".equals(result)){
						Toast.makeText(ListarClienteActivity.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
					}else{
						try {
							
							JSONArray peliculasJSONArray = new JSONArray(result);
							int cantPeliculas = peliculasJSONArray.length();
							for(int i = 0; i< cantPeliculas; i ++){
									Node mynode = new Node();
									mynode.nombrePaciente  = peliculasJSONArray.getJSONObject(i).getString("nombre");
									mynode.rutPaciente = peliculasJSONArray.getJSONObject(i).getString("rut");
									mynode.direccionPaciente = peliculasJSONArray.getJSONObject(i).getString("direccion");
									mArray.add(mynode);
							}
							  carga();
						} catch (JSONException e) {
							Toast.makeText(ListarClienteActivity.this, "2.Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
						}
					}
				}
		    }
		
}
